package me.yricky.cov_spectrum.model

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class UserConfig(
    private val save:(ConfigItem)->Unit,
    private val load:()->ConfigItem,
    private val scope:CoroutineScope
) {

    private val _configItem = MutableStateFlow(ConfigItem(""))
    val asState = _configItem.asStateFlow()
    fun get() = _configItem.value

    fun set(item:ConfigItem.()->ConfigItem){
        scope.launch(Dispatchers.IO) {
            save(item(_configItem.value))
            _configItem.value = load()
        }
    }

    init {
        scope.launch {
            withContext(Dispatchers.IO){
                _configItem.value = load()
            }
        }
    }
    data class ConfigItem(
        val accessKey:String = "",
    )
}